package sicnu.cs.ich.activity.rest;

import com.github.pagehelper.PageInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import sicnu.cs.ich.activity.service.IActivityParticipateService;
import sicnu.cs.ich.activity.service.IActivityService;
import sicnu.cs.ich.activity.service.ICommentService;
import sicnu.cs.ich.api.common.ResultInfo;
import sicnu.cs.ich.api.common.enums.FileEnum;
import sicnu.cs.ich.api.domain.entity.ActivityImg;
import sicnu.cs.ich.api.domain.entity.ActivityParticipate;
import sicnu.cs.ich.api.domain.entity.UserInfo;
import sicnu.cs.ich.api.domain.form.AddCallForm;
import sicnu.cs.ich.api.domain.form.PageParam;
import sicnu.cs.ich.api.domain.vo.UserInfoVo;
import sicnu.cs.ich.common.services.IFileUploadService;
import sicnu.cs.ich.common.util.ResultInfoUtil;
import sicnu.cs.ich.security.domain.entity.User;
import sicnu.cs.ich.security.util.SecurityUtil;

import javax.validation.Valid;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import static sicnu.cs.ich.common.util.FileUtils.isImage;

/**
 * @author 黎琦
 * @date 2021/11/25 23:31
 **/
@RestController
@Slf4j
@RequiredArgsConstructor
@RequestMapping("/activity")
@Api(tags = {"活动相关操作(需要登录)"})
public class ActivityResource {
    private final IActivityService activityService;
    private final ICommentService commentService;
    private final IFileUploadService fileUploadService;
    private final IActivityParticipateService activityParticipateService;

    @GetMapping("/addCheck")
    @ApiOperation("添加活动前检测是否是机构认证")
    public ResultInfo<Void> isCertified(){
        return SecurityUtil.hasAuthority("act:activity:add")?
                ResultInfoUtil.buildSuccess("已认证"):ResultInfoUtil.buildError("未认证");
    }

    @PostMapping("/activityInfo")
    @ApiOperation("添加活动")
    @PreAuthorize("hasAuthority('act:activity:add')")
    public ResultInfo<Integer> addActivity(@Valid AddCallForm addCallForm, MultipartFile[] publicImgs) throws IOException {
        // 验证文件格式
        if(publicImgs==null){
            return ResultInfoUtil.buildError("封面图片不能为空");
        }
        //验证文件格式
        var fileList = isImage(publicImgs);
        //将图片放到数组中传入service层
        //将第一章封面图片放到addCallForm中
        String filePath = fileUploadService.uploadFile((FileInputStream) publicImgs[0].getInputStream(), FileEnum.ACTIVITY_COVER_IMG, publicImgs[0].getOriginalFilename());
        addCallForm.setPublicImg(filePath);
        //后面的图片需要有图片描述（暂时不启用）
        ArrayList<ActivityImg> images = new ArrayList<>();
        for (int i=1;i<publicImgs.length;i++) {
            filePath = fileUploadService.uploadFile((FileInputStream) publicImgs[i].getInputStream(), FileEnum.ACTIVITY_COVER_IMG, publicImgs[i].getOriginalFilename());
//            images.add(ActivityImg.builder().img(filePath).remark(imgRemarks[i-1]).build());
            images.add(ActivityImg.builder().img(filePath).build());
        }
        Integer aid = activityService.insert(addCallForm, SecurityUtil.getCurrentUserId(),0,images);
        return ResultInfoUtil.buildSuccess(aid);
    }

    @PostMapping("/participant")
    @ApiOperation("参加活动")
    @PreAuthorize("hasAuthority('')")
    public ResultInfo<Void> participate(@RequestParam(value = "acID") Integer aid){
        return activityService.participate(aid, SecurityUtil.getCurrentUserId());
    }

    @GetMapping("/participantList/{acID}")
    @ApiOperation("获取活动参与者列表")
    public ResultInfo<PageInfo<UserInfoVo>> participantList(@PathVariable("acID") Integer aid,
                                                            @RequestBody PageParam param){
        if (aid==null){
            return ResultInfoUtil.buildError("活动id不能为空");
        }
        return ResultInfoUtil.buildSuccess(activityParticipateService.getParticipateList(aid, param));
    }

    /**
     * 处理活动报名者，这里一次性处理一个活动的
     * @param activityParticipates
     * @return
     */
    @PutMapping("/participant")
    @PreAuthorize("hasAuthority('act:call:add')")
    @ApiOperation("批量处理活动报名者（是否通过）")
    public ResultInfo<Void> pass(@Valid List<ActivityParticipate> activityParticipates){
        activityParticipateService.pass(activityParticipates);
        return ResultInfoUtil.buildSuccess();
    }

    @GetMapping("/stopApply")
    @ApiOperation("停止报名")
    @PreAuthorize("hasAuthority('act:call:add')")
    public ResultInfo<Void> stopApply(@RequestParam("acID") Integer aid){
        // FIXME 这里不对请求的人鉴权吗
        if (aid==null){
            return ResultInfoUtil.buildError("活动id不能为空");
        }


        activityService.stopApply(aid);
        return ResultInfoUtil.buildSuccess();
    }
}
